package net.yb.service.impl;

import net.yb.dao.CategoryDao;
import net.yb.dao.ProductDao;
import net.yb.dao.impl.CategoryDaoImpl;
import net.yb.dao.impl.ProductDaoImpl;
import net.yb.entity.Category;
import net.yb.entity.Product;
import net.yb.exception.CategoryNotExistException;
import net.yb.exception.ProductNotExistsException;
import net.yb.service.ProductService;

import java.util.List;

/**
 * 商品业务实现类
 */
public class ProductServiceImpl implements ProductService {

    CategoryDao categoryDao = new CategoryDaoImpl();
    ProductDao productDao = new ProductDaoImpl();

    @Override
    public void add(Product product) {
        // 判断商品分类是否存在
        Category category = categoryDao.selectById(product.getCategory().getCid());
        if (category == null){
            throw new CategoryNotExistException("商品分类不存在！");
        }

        // 添加商品
        productDao.insert(product);
    }

    @Override
    public List<Product> findAll() {
        return productDao.selectAll();
    }

    @Override
    public void modify(Product product) {
        // 判断商品是否存在
        Product p = productDao.selectById(product.getPid());
        if (p == null){
            throw new ProductNotExistsException("商品不存在！");
        }

        // 判断商品分类是否存在
        Category category = categoryDao.selectById(product.getCategory().getCid());
        if (category == null){
            throw new CategoryNotExistException("商品分类不存在！");
        }

        // 修改商品
        productDao.updateById(product);
    }

    @Override
    public void removeById(int id) {
        // 判断商品是否存在
        Product p = productDao.selectById(id);
        if (p == null){
            throw new ProductNotExistsException("商品不存在！");
        }

        // 删除商品
        productDao.deleteById(id);
    }

    @Override
    public Product findById(int id) {
        return productDao.selectById(id);
    }

    @Override
    public List<Product> findByName(String name) {
        return productDao.selectByName(name);
    }

    @Override
    public List<Product> findByPrice(double minPrice, double maxPrice) {
        return productDao.selectByPrice(minPrice, maxPrice);
    }
}
